<?php

namespace Admin\Controller;

use Core\Constant;
use Core\Controller\AdminBaseController;
use Core\Exception\BusinessException;
use Core\Helper\AdminInputHelper;
use Core\Helper\CommonHelper;
use Core\Helper\DatabaseHelper;
use Core\Session\AdminSessionHelper;
use Exception;
use Logger;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;


class RestaurantController extends AdminBaseController {
    public function indexAction() {

    }

    public function listAction()
    {

        try{

            $restaurantTable = $this->getTableFinder()->getRestaurantTable();

            $searchOption = array();


            $sortData = $this->params()->fromPost("sort");
            if($sortData){
                $order = array();
                foreach ($sortData as $sortField) {
                    $field = $sortField['field'];
                    $direction = $sortField['dir'];
                    $orderClause = $field." ".$direction;
                    array_push($order, $orderClause);
                }
            }else{
                $order = array("id desc");
            }

            $page = $this->params()->fromPost("page");
            $rows = $this->params()->fromPost("pageSize");
            $offset = ($page - 1) * $rows;
            $allPages = $restaurantTable->search(true, $offset, $rows, $order,$searchOption);
            return new JsonModel(array('success'=>true,
                'rows'=>$allPages["rows"]->toArray(),
                'total'=>$allPages["total"]));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function addAction(){
        try{

            $provinceTable = $this->getTableFinder()->getProvinceTable();
            $allProvinces = $provinceTable->getAllAsArray();
            $viewModel = new ViewModel(array('allProvinces'=>$allProvinces));
            return $viewModel;

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function templateGroupListAction(){
        try{
        $domainTemplateGroupTable = $this->getTableFinder()->getDomainTemplateGroupTable();
            $allTemplate = $domainTemplateGroupTable->getAllAsArray();
        return new JsonModel($allTemplate);
          }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function addRestaurantAction(){
        try{

            $name = $this->params()->fromPost('name');
            $provinceId = $this->params()->fromPost('provinceId');
            $districtId = $this->params()->fromPost('districtId');
            $address = $this->params()->fromPost('address');
            $longitude = $this->params()->fromPost('longitude');
            $latitude = $this->params()->fromPost('latitude');
            $restaurant_phone = $this->params()->fromPost('restaurant_phone');
            $restaurant_email = $this->params()->fromPost('restaurant_email');
            $website = $this->params()->fromPost('website');
            $boss_name = $this->params()->fromPost('boss_name');
            $boss_phone = $this->params()->fromPost('boss_phone');
            $boss_email = $this->params()->fromPost('boss_email');
            $tmpArr = explode('@',$boss_email);
            $username = $tmpArr[0];
            $password = $this->params()->fromPost('password');
            $retype_password = $this->params()->fromPost('retype_password');
            $template_group_id = $this->params()->fromPost('template_group_id');
            $user_id = $this->params()->fromPost('user_id');
            $domain = CommonHelper::vietnameseToASCII($name);

            //validate
            //check if name exist
            $name = AdminInputHelper::filterDomainName($name);
            $validatorDto = AdminInputHelper::validateDomainName($name);
            if(!$validatorDto->isValid()) throw new BusinessException($validatorDto->getMessageStr());

            $restaurantTable = $this->getTableFinder()->getRestaurantTable();
            $rs = $restaurantTable->getByColumn('domain', $domain);
            if($rs->count() > 0) throw new BusinessException('Đã tồn tại nhà hàng có tên:'.$name);
            //check if password the same
            $validatorDto = AdminInputHelper::validatePassword($password);
            if(!$validatorDto->isValid()) throw new BusinessException($validatorDto->getMessageStr());

            if($password !== $retype_password) throw new BusinessException('Password không giống nhau');
            //end validate

            $addressTable = $this->getTableFinder()->getAddressTable();
            $addressId = $addressTable->insert(array('district_id'=>$districtId, 'province_id'=>$provinceId,
            'detail'=>$address, 'long'=>$longitude, 'lat'=>$latitude, 'detail_en'=>$address));

            $restaurantId = $restaurantTable->insert(array('domain'=>$domain, 'name'=>$name,
            'address_id'=>$addressId, 'email'=>$restaurant_email, 'phone'=>$restaurant_phone,'active'=>1,
            'status'=>Constant::$RESTAURANT_STATUS_INACTIVE));

            // create domain config
            $domainConfigTable = $this->getTableFinder()->getDomainConfigTable();
            $domainConfigTable->insert(array('restaurant_id'=>$restaurantId,
                'dtg_id'=>$template_group_id));
            //set sample data to domain_config property

            //create boss of restaurant
            $userTable = $this->getTableFinder()->getUserTable();
            $password = $this->getDigestService()->getUserPassword($boss_email, $password);
            if($user_id)
                $user = $userTable->getUser($user_id);
            else{
                $user_id = $userTable->insert(array('name'=>$boss_name,'phone_number'=>$boss_phone,
                    'email'=>$boss_email, 'password'=>$password, 'username'=>$username));
                $user = $userTable->getUser($user_id);
            }

            //assign role to user
            $roleTable = $this->getTableFinder()->getRoleTable();
            $role = $roleTable->getRoleByCode(Constant::$SYSTEM_ROLE_CODE_MEMBER);
            $user->addRole($role->id);
            $role = $roleTable->getRoleByCode(Constant::$SYSTEM_ROLE_CODE_RES_STAFF);
            $user->addRole($role->id);

            //them domain user cho boss
            $domainUserTable = $this->getTableFinder()->getDomainUserTable();
            $domainUserTable->insert(array( 'domain_id'=>$restaurantId, 'user_id'=>$user_id,
            'is_boss'=>1));

            //tao ban ghi balance cho user
            $userBalanceTable = $this->getTableFinder()->getUserBalanceTable();
            $userBalanceTable->insert(array('user_id'=>$user_id, 'balance'=>0));

            //insert to domain_page

            //create database of restaurant
            DatabaseHelper::createRestaurantDb($domain);

            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

}